<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" >
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordquery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pet" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本" width="100" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="市场价" width="120"  sortable>
      </el-table-column>
      <el-table-column prop="petType.name" label="类型" width="120"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span  v-else="scope.row.state==0">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="120" sortable>
      </el-table-column>
      <el-table-column prop="user" label="领养人" width="120" sortable>
        <template slot-scope="scope">
          <span style="color: #f4606c" v-if="scope.row.user">{{scope.row.user.username}}</span>
          <span style="color: #ff9900" v-else>暂无领养人</span>
        </template>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="120" sortable>
        <template slot-scope="scope">
          <span style="color: #800073" v-if="scope.row.searchMasterMsgId">来自于寻主消息</span>
          <span style="color: #ff6f00" v-else>来自于店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button type="primary" icon="el-icon-save" circle @click="handlesave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="total,sizes, prev, pager, next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="sizes"
          :page-size="pageSize"
          :total="totals"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加修改-->
    <!--编辑界面-->
    <!--
      title="添加或修改" - 标题
      :visible.sync="saveFormVisible" - 控制当前对话框是否显示 - 默认为false不显示
      :close-on-click-modal="false" - 点击对话框以外的区域不关闭
    -->
    <el-dialog title="添加或修改" :visible.sync="saveFormVisible" :loading="saveLoading" :close-on-click-modal="false" >
      <!--
        :model="saveForm"  - 表单绑定模型数据对象saveForm
        label-width="80px"  - 标签的宽度
        :rules="saveFormRules" - 验证规则 - 表单项校验
        ref="saveForm" - 为当前对话框取名saveForm - 做表单校验

        label="姓名" - 标签名字
        prop="name" - 要做校验的时候必须要，不做校验就没有必要
        v-model="saveForm.name" - 双向绑定
        auto-complete="off" - 自动完成 - 关闭
      -->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" >
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" >
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型" >
          <el-cascader v-model="saveForm.typeId"
                       :options="petTree"
                       :props="{
            	      checkStrictly: true,
                    label: 'name', // 级联框显示那个属性的值
                    value: 'id'    // 回显时需要,回传值的时候也需要
                    }" clearable></el-cascader>
        </el-form-item>

        <el-form-item prop="logo" label="图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属店铺" >
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" >提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';


export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      //1.分页相关参数
      pet: [],     //绑定到表格 - 显示列表数据 - 请求完成之后
      totals: 0,          //总数量 - 计算分页栏 -  请求完成之
      currentPage: 1,     //当前页 - 分页栏默认当前页显示
      pageSize: 5,        //每页显示的条数  - 计算分页栏
      sizes:[5, 10, 20, 50],
      listLoading: false, //表格上的加载框

      //2.高级查询相关数据
      keyword: "",

      //3.批量删除相关参数
      sels: [],

      //4.添加或修改的相关数据
      saveFormVisible: false, //控制对话框是否显示 - 默认不显示
      saveLoading: false,     //保存的加载框 - 默认不显示
      saveFormRules: {        //表单项验证
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ]
      },
      //5.添加和修改中对话框的数据
      saveForm: {
        id:null,
        name: null,
        costprice: null,
        saleprice: null,
        typeId:null,
        resources: null,
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },

      //6.回显部门名称选择器相关数据
      shops: [],
      //7.宠物树数据
      petTree:[],
      //文件上传相关数据
      fileList: [],
    }
  },
  methods: {
    //1.每页条数
    handleSizeChange(val) {
      this.pageSize=val;
      this.getpet();
    },
    //2.当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getpet();
    },
    //3.高级查询
    keywordquery(){
      this.currentPage=1;
      this.getpet();
    },
    //1.获取用户列表
    getpet() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;

      this.$http.post("/pet",para).then(res=>{

        //给totals赋值 - 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 - 显示当前页的分页数据
        this.pet = res.data.data;
        //隐藏加载框/忙等框
        this.listLoading = false;
      }).catch(res=> {
        this.$message.error('系统繁忙，请稍后重试!!!');
      })
    },
    //2.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/pet/"+row.id).then((res)=>{
          this.listLoading = false;
          if (res.data.success){
            this.$message.success("删除成功");
            if(((this.currentPage*this.pageSize)-this.totals)>=(this.pageSize-1)){
              this.currentPage=this.currentPage-1;
            }
            this.getpet();
          }else {
            this.$message.error("系统繁忙，请稍后再试！！！");
          }
        }).catch((res) => {
          this.$message.error("系统繁忙，请稍后再试！！！");
        });
      }).catch(()=>{

      })
    },
    //3.批量删除
    selsChange: function (sels) {
      this.sels = sels;
    },
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      console.log(ids);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then((res) => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success("删除成功");
            this.currentPage =1;
            this.getpet();
          } else {
            this.$message.error("系统繁忙，请稍后再试  500！！！");
          }
        }).catch((res) => {
          this.$message.error("系统繁忙，请稍后再试 400！！！");
        });
      }).catch(() => {

      });
    },

    //4.显示编辑界面
    handlesave:function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      this.getpetTree();
      this.getshops();
      this.fileList= [];
      if (this.saveForm.resources){
        this.fileList = [];
        var arr = this.saveForm.resources.split(",")
        for (var url of arr) {
          this.fileList.push({"url": "http://123.207.27.208" +url})
        }
      }

    },
    //5.显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm  = {
        id:null,
        name: null,
        costprice: null,
        saleprice: null,
        typeId:null,
        resources: null,
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      };
     this.getpetTree();
     this.getshops();
      //文件上传相关数据
      fileList: [];
    },

    //6.添加修改
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            let arr=para.typeId;
            if (Array.isArray(arr)){
              if (arr.length==0){
                para.typeId=null;
              }else {
                para.typeId=arr[arr.length-1];
              }
            }

            this.$http.put("/pet", para).then((res) => {
              this.saveLoading = false;
              this.saveFormVisible = false;
              if (res.data.success) {
                this.$message.success("操作成功");
                this.getpet();
              }else {
                this.$message.error("系统繁忙，请稍后再试！！！");
              }
            }).catch((res)=>{
              this.$message.error("系统繁忙，请稍后再试！！！");
            });
          });
        }
      }).catch(()=>{

      });
    },

    //7.获取  宠物树
    getpetTree(){
      this.$http.get("/petType/getTree").then((res)=>{
        this.petTree=res.data;
      })
    },

    //8.获取所有店铺
    getshops(){
      this.$http.get("/shop").then((res)=>{
        this.shops=res.data;
      })
    },

    //9.文件上传的业务逻辑
    handleSuccess(response, file, fileList){
      // console.log(response);
      //文件上传相关数据
      if (this.saveForm.resources){
        this.saveForm.resources +=","+ response.resultObj;
      }else {
        this.saveForm.resources =response.resultObj;
      }
      //2.对fileList的处理 - 前端显示图片的
      if (this.saveForm.resources){
        this.fileList = [];
        var arr = this.saveForm.resources.split(",")
        for (var url of arr) {
          this.fileList.push({"url": "http://123.207.27.208" +url})
        }
      }
      console.log(this.fileList)
    },

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      console.log(file);
      var filePath =file.url.substring(file.url.indexOf("/group1")); // /group1/M00/01/B0/CgAIC2MdsaSAVKcaAAFHUm1b1JI875.png
      this.$http.delete("/fastDfs?path="+filePath).then(res=>{
        if(res.data.success){
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        }else{
          this.$message({
            message: '删除失败!',
            type: 'error'
          });
        }
      })
      //2.对resource做处理
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          if(filePath==item){//找到了删除的图片
            arr.splice(i,1);//删除指定的图片
          }
        }
        this.saveForm.resources = arr.join(",")
      }
      //3.对fileList的处理 - 前端显示图片的
      this.fileList = [];
      if (this.saveForm.resources) {
        var arr = this.saveForm.resources.split(",");
        for (var i = 0; i < arr.length; i++) {
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url": "http://123.207.27.208" + item});
        }
      }
    },

    //上架
    onsale(){
      if (this.sels.length==0){
        this.$message.warning("请选择宠物再上架！")
        return;
      }
        var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/onsale",ids).then((res) => {
          if (res.data.success) {
            this.$message.success("上架成功");
            this.getpet();
          } else {
            this.$message.error(res.data.msg);
          }

        }).catch((res) => {
          this.$message.error("系统繁忙，请稍后再试 400！！！");
        });
      }).catch(() => {
      });
    },
    offsale(){
      if (this.sels.length==0){
        this.$message.warning("请选择宠物再下架！")
        return;
      }
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/offsale",ids).then((res) => {
          if (res.data.success) {
            this.$message.success("下架成功");
            this.getpet();
          } else {
            this.$message.error("系统繁忙，请稍后再试  500！！！");
          }
        }).catch((res) => {
          this.$message.error("系统繁忙，请稍后再试 400！！！");
        });
      }).catch(() => {
      });
    }
  },
  mounted() {
    this.getpet();
  }
}
</script>

<style scoped>

</style>